package com.qingmu.club.minaapi.controller.club;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.qingmu.club.minaapi.custom.logic.ExamItemLogic;
import com.qingmu.club.minaapi.custom.logic.UsersWxLogic;
import com.qingmu.club.minaapi.custom.service.CustomClubStaffScoreService;
import com.qingmu.club.minaapi.model.QueryExamItemModel;
import com.qingmu.club.minaapi.model.QueryGrowCollegeModel;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.ConvertUtil;
import com.qingmu.club.minaapi.utils.KeyValueDefine;
import com.qingmu.club.minaapi.utils.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 * 成长学堂 前端控制器
 * </p>
 *
 * @author duke
 * @since 2019-08-20
 **/

@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "成长学堂(俱乐部端小程序)", description = "成长学堂(俱乐部端小程序)")
@RequestMapping("/club/grow")
public class ClubGrowController {

    @Autowired
    GrowCollegeService growCollegeService;

    @Autowired
    ExamItemDetailService examItemDetailService;

    @Autowired
    UsersWxLogic usersWxLogic;

    @Autowired
    ClubStaffExamService clubStaffExamService;

    @Autowired
    ExamItemService examItemService;

    @Autowired
    ExamItemLogic examItemLogic;

    @Autowired
    ClubStaffService clubStaffService;

    @Autowired
    ClubShopService clubShopService;

    @Autowired
    ClubStaffScoreService clubStaffScoreService;

    @Autowired
    GrowCollegeCategoryService growCollegeCategoryService;

    @Autowired
    CustomClubStaffScoreService customClubStaffScoreService;

    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "成长学堂列表")
    public ResponseEntity list(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }
        QueryWrapper<GrowCollegeCategory> queryWrapper = new QueryWrapper();
        queryWrapper.eq(GrowCollegeCategory.STATUS, KeyValueDefine.ONLINE_STATUS).orderByAsc(GrowCollegeCategory.SORT);
        List<GrowCollegeCategory> growCollegeCategories = this.growCollegeCategoryService.list(queryWrapper);

        List<HashMap<String,Object>> categoryList = new ArrayList<>();
        for(GrowCollegeCategory growCollegeCategory : growCollegeCategories){
            QueryWrapper<GrowCollege> qw = new QueryWrapper();
            qw.eq(GrowCollege.STATUS, KeyValueDefine.ONLINE_STATUS).eq(GrowCollege.CATEGORY_ID,growCollegeCategory.getId());

            List<GrowCollege> growCollegeList = this.growCollegeService.list(qw);
            if(!CollectionUtils.isEmpty(growCollegeList)){
                HashMap<String,Object> hashMap = ConvertUtil.objectToMap(growCollegeCategory);
                hashMap.put("growCollegeList",growCollegeList);
                categoryList.add(hashMap);
            }
        }

        return ResponseObject.success(categoryList);
    }


    @RequestMapping(value = "/getById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "学堂详情")
    public ResponseEntity getById(
            @ApiParam(required = true, value = "成长学堂id") @RequestParam(required = true) String growId,
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String staffId
    ) {
        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }

        GrowCollege growCollege = this.growCollegeService.getById(growId);
        if(growCollege==null){
            return ResponseObject.error(560,"成长学堂信息不存在");
        }


        Map<String, Object> map = new HashMap<>();
        map.put("staff_id",clubStaff.getId());
        map.put("club_id",clubStaff.getClubId());
        map.put("grow_college_id", growId);

        QueryWrapper<ClubStaffScore> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(ClubStaffScore.STAFF_ID,staffId)
                .eq(ClubStaffScore.GROW_COLLEGE_ID,growId);
        List<ClubStaffScore> clubStaffScoreList = this.clubStaffScoreService.list(queryWrapper);

        QueryGrowCollegeModel item = new QueryGrowCollegeModel();
        Map<String, Object> map1 = this.customClubStaffScoreService.staffScoreSum(map);
        item.setStudySum(clubStaffScoreList.size());
        item.setScoreSum(map1==null?Double.valueOf(0.0):(Double) map1.get("scoreSum"));

        item.setExam(true);
        BeanUtils.copyProperties(growCollege, item);

        return ResponseObject.success(item);
    }


    @RequestMapping(value = "/queryItemList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询题目列表")
    public ResponseEntity queryItemList(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "成长学堂id") @RequestParam(required = true) String growId
    ) {
        ClubStaff clubStaff = this.usersWxLogic.getClubStaff(staffId);
        if (clubStaff == null) {
            return ResponseObject.error(401, "人员信息找不到");
        }

        GrowCollege growCollege = this.growCollegeService.getById(growId);
        if (growCollege == null) {
            return ResponseObject.error(556, "成长学堂找不到");
        }

        QueryWrapper<ExamItem> qw = new QueryWrapper();
        qw.eq(ExamItem.GROW_COLLEGE_ID, growId);
        List<ExamItem> examItemList = this.examItemService.list(qw);

        int itemIndex = 0;
        List<QueryExamItemModel> results = new ArrayList();

        //随机返回题目数
        List<ExamItem> newExamItemList = new ArrayList<>();
        int returnItem = growCollege.getItemTotal();//返回的题目数

        //下标不能重复
        Set<Integer> set = new HashSet<Integer>();
//        for (int i = 0 ;i<returnItem;i++) {
        while (set.size() < returnItem) {
            Random random = new Random();
            int num = random.nextInt(examItemList.size());
            set.add(num);
        }
//        }

        if (returnItem < examItemList.size()) {
            for (Integer integer : set) {
                newExamItemList.add(examItemList.get(integer));
            }
        } else {
            newExamItemList = examItemList;
        }


        for (ExamItem examItem : newExamItemList) {
            int itemSum = examItemList.size();
            itemIndex++;

            QueryWrapper<ExamItemDetail> qw2 = new QueryWrapper();
            qw2.eq(ExamItemDetail.EXAM_ITEM_ID, examItem.getId());
            List<ExamItemDetail> examItemDetailList = this.examItemDetailService.list(qw2);

            QueryExamItemModel item = new QueryExamItemModel();
            item.setItemIndex(Integer.valueOf(itemIndex));
            item.setItemSum(Integer.valueOf(itemSum));
            item.setExamItemDetailList(examItemDetailList);
            BeanUtils.copyProperties(examItem, item);

            results.add(item);
        }
        return ResponseObject.success(results);
    }

    @RequestMapping(value = "/staffToLearn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "教练学习")
    public ResponseEntity staffToLearn(
            @ApiParam(required = true, value = "人员id") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "学习时长") @RequestParam(required = true) Double studyHours,
            @ApiParam(required = true, value = "成长学堂id") @RequestParam(required = true) String growCollegeId
    ) {

        ClubStaff clubStaff =this.usersWxLogic.getClubStaff(staffId);
        if(clubStaff==null){
            return ResponseObject.error(401,"人员信息找不到");
        }

        ClubShop clubShop = this.clubShopService.getById(shopId);
        if(clubShop==null){
            return ResponseObject.error(556,"店铺找不到");
        }

        ClubStaffScore clubStaffScore = new ClubStaffScore();
        clubStaffScore.setShopId(shopId);
        clubStaffScore.setStaffId(staffId);
        clubStaffScore.setStudyHours(studyHours);
        clubStaffScore.setGrowCollegeId(growCollegeId);
        clubStaffScore.setStaffName(clubStaff.getStaffName());
        clubStaffScore.setStaffAvatar(clubStaff.getAvatar());
        clubStaffScore.setShopName(clubShop.getShopName());
        clubStaffScore.setClubId(clubShop.getClubId());
        //clubStaffScore.setStudyNum(1);
        clubStaffScore.setType(KeyValueDefine.STUDY);
        boolean state = this.clubStaffScoreService.save(clubStaffScore);
        if(!state){
            return ResponseObject.error();
        }
        return ResponseObject.success();
    }

    @RequestMapping(value = "/exam", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "考评")
    public ResponseEntity exam(
            @RequestBody List<ClubStaffExam> clubStaffExamList
    ) {
        Integer examSuccess = 0;
        Integer examError = 0;
        String growCollegeId = clubStaffExamList.get(0).getGrowCollegeId();
        GrowCollege growCollege = this.growCollegeService.getById(growCollegeId);
        ClubStaff clubStaff = this.clubStaffService.getById(clubStaffExamList.get(0).getStaffId());
        for (ClubStaffExam clubStaffExam : clubStaffExamList) {
            boolean falg = this.examItemLogic.ItemDetailTrueOrFalse(clubStaffExam.getExamItemId(), clubStaffExam.getExamItemDetailIds());

            if (falg) {
                examSuccess += 1;
                clubStaffExam.setIsTrue(1);
            } else {
                examError += 1;
                clubStaffExam.setIsTrue(0);
            }
            boolean state = this.clubStaffExamService.save(clubStaffExam);
            if (!state) {
                return ResponseObject.error();
            }
        }


        HashMap<String, Object> hashMap = new HashMap<>();
        ClubStaffScore clubStaffScore = new ClubStaffScore();
        clubStaffScore.setStaffId(clubStaff.getId());
        clubStaffScore.setGrowCollegeId(growCollegeId);
        clubStaffScore.setStaffName(clubStaff.getStaffName());
        clubStaffScore.setStaffAvatar(clubStaff.getAvatar());
        //clubStaffScore.setStudyNum(1);
        clubStaffScore.setClubId(growCollege.getClubId());
        clubStaffScore.setExamError(examError);
        clubStaffScore.setExamSuccess(examSuccess);
        clubStaffScore.setExamScore(examSuccess * growCollege.getItemAvgScore());
        //clubStaffScore.setExamNum(1);
        clubStaffScore.setType(KeyValueDefine.EXAM);
        boolean state = this.clubStaffScoreService.save(clubStaffScore);
        if (!state) {
            return ResponseObject.error();
        }
        hashMap = ConvertUtil.objectToMap(clubStaffScore);

        Map<String, Object> map = new HashMap<>();
        map.put("staff_id", clubStaff.getId());
        map.put("club_id", clubStaff.getClubId());
        map.put("grow_college_id", growCollegeId);
        Map<String, Object> map1 = this.customClubStaffScoreService.staffScoreSum(map);
        hashMap.put("levelNum", this.customClubStaffScoreService.staffScoreRanking(map).get("rank"));
        hashMap.put("scoreSum",map1==null? 0:map1.get("scoreSum"));

        return ResponseObject.success(hashMap);
    }

}

